from django.shortcuts import render_to_response, get_object_or_404
from django.http import Http404, HttpResponse
from movies.models import *
from django.conf import settings
from django.core import serializers

import os
import re
import imdb
import sys
import urllib2

def index(request):
	all_movies = Movie.objects.filter(active=True)
	plot_list = Plot.objects.order_by('title')
	ratings = Certificate.objects.order_by('id')
	return render_to_response('movies/index.html', {'object_list': all_movies, 'plot_list': plot_list , 'ratings': ratings})
	
def detail(request, movie_id):
	movie = get_object_or_404(Movie, pk=movie_id)
	return render_to_response('movies/detail.html', {'movie': movie})

def fetch_movie_info(request, id):
	response = HttpResponse()
	toreturn = list(Movie.objects.select_related().filter(id=id)) + list(list(Plot.objects.filter(movie=id)))
	json_serializer = serializers.get_serializer("json")()
	json_serializer.serialize(toreturn, ensure_ascii=False, stream=response)
	return response
	
def runparser():
	# open file system handle
	movies = os.listdir(settings.FILES_PATH)
	movies.sort()
	
	# connect to imdb
	i = imdb.IMDb(accessSystem='http')
	count = 0
	output = ''
	for fname in movies:
		#if count > 0:
		#	beeak
		
		if fname == '.directory':
			continue # .dieectory isn't a movie!
		# remove .avi from the filename. If this is a directory, nothing happens here.
		fname = fname.replace ('.avi', '')
		
		# check if file is already in database, if so, ignore
		moviefile, created = MovieFile.objects.get_or_create(file_name__exact=fname)
		moviefile.file_name = fname
		moviefile.save()
		print 'For filename %s got' % moviefile.file_name
		if created:
			count = count + 1
			# new movie object has been created
			ml = i.search_movie(fname)
			
			# gets all movies for a file name
			mcount = 0
			for m in ml:	
				try:
					i.update(m, ['main', 'plot', 'vote_details'])
				except:
					output = output.join('error with %s' % m['title'])
				movie = Movie.objects.create(moviefile=moviefile)
				
				# if this is the first movie for this moviefile, set to true
				if mcount == 0:
					movie.active = True
				
				if mcount >= settings.EXTRA_FETCH:
					break

				mcount = mcount + 1	
				# get the imdb, do initial save
				movie.imdb_id = str(i.get_imdbID(m))
				movie.save()
				
				try:
					title = m['title']
					#movie.title = unicode(movie.title, errors='ignore')
				except:
					title = fname
					#print '[Failed] Movie title %s' % movie.title
				try:
					movie.title_long = m['long imdb title']
					#movie.long_title = unicode(movie.long_title, errors='ignore')
				except:
					movie.title_long = title
				try:
					movie.title_cano = m['canonical title']
					#movie.cano_title = unicode(movie.cano_title, errors='ignore')
				except:
					movie.title_cano = title
				try:
					movie.title_long_cano = m['long imdb canonical title']
					#movie.long_cano_title = unicode(movie.long_cano_title, errors='ignore')
				except:
					movie.title_long_cano = title
				try:
					movie.imdb_rating = float(m['rating'])
					#movie.rating = unicode(movie.rating, errors='ignore')
				except:
					movie.imdb_rating = '0'
				try:
					movie.year = int(m['year'])
					#movie.year = unicode(movie.year, errors='ignore')
				except:
					movie.year = 1900
				try:
					cover_url = str(m['cover url'])
					#movie.cover_url = unicode(movie.cover_url, errors='ignore')
					#fetch_cover (cover_url, settings.COVER_PATH + movie.imdb_id + '.jpg')
					filein = urllib2.urlopen(cover_url)
					fileout = open (settings.COVER_PATH + movie.imdb_id + '.jpg')
					while True:
						try:
							bytes = filein.read(1024)
							fileout.write(bytes)
						except IOError, (errno, strerror):
							pass
					if bytes <> "":
						filein.close()
						fileout.close()

				except:
					cover_url = ''
				try:
					runtime = m['runtimes'][0]
					movie.runtime = int(re.findall('[0-9]+', runtime)[0])
				except:
					runtime = 0
				try:
					movie.mpaa_warning = m['mpaa']
					#mpaa = unicode(mpaa, errors='ignore')
				except:
					movie.mpaa_warning = ''
				try:
					genres = m['genres']
					for g in genres:
						go = Genre.objects.get_or_create(name=g)
						movie.genre.add(go[0])
				except:
					pass
				
				try:
					certs = m['certificates']
					for acert in certs:
						split = acert.split(':')
						c = Certificate.objects.get_or_create(rating=split[1], country=split[0])
						movie.mpaa_rating.add(c[0])
				except:
					pass
				
				# final save of movie
				movie.title = title
				movie.cover_url = cover_url
				movie.save()
				
				# add the plot once we have saved the movie
				try:
					plots = m['plot'] # Use the first result
					# Clear the beginning info about the person who submitted the plot info.
					for plot in plots:
						split = plot.split('::')
						Plot.objects.get_or_create(author=split[0], text=split[1], movie=movie)
				except:
					plot = ''
	
				print '\t %s' % movie.title
	return HttpResponse(output)

#def fetch_cover(inurl, outfile):
#	filein = urllib2.urlopen(inurl)
#	fileout = open(outfile, 'w')
#	while True:
#		try:
#			bytes = filein.read(1024)
#			fileout.write(bytes)
#		except IOError, (errno, strerror):
#			pass
#	
#	if bytes <> "":
#		filein.close()
#		fileout.close()
#	return outfile
